package indi.kider.server.applet.service;

import com.google.common.base.Strings;
import indi.kider.common.constant.AppUserType;
import indi.kider.common.model.apabus.Notice;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apartment.DevLockCard;
import indi.kider.common.model.apartment.DevLockFingerPrint;
import indi.kider.common.model.apartment.DevLockPassword;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.model.employee.Employee;
import indi.kider.common.model.employee.Tenant;
import indi.kider.common.model.employee.Waiter;
import indi.kider.common.model.employee.Worker;
import indi.kider.common.model.woniubus.DevSensetimeUpload;
import indi.kider.common.model.woniubus.TenantInHouse;
import indi.kider.server.apabus.mapper.NoticeMapper;
import indi.kider.server.apabus.mapper.RentMapper;
import indi.kider.server.apartment.mapper.*;
import indi.kider.server.applet.model.User;
import indi.kider.server.applet.util.DateTool;
import indi.kider.server.employee.mapper.*;
import indi.kider.server.employee.model.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
@SuppressWarnings("ALL")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper               userMapper;
    @Autowired
    private TenantMapper             tenantMapper;
    @Autowired
    private EmployeeMapper           employeeMapper;
    @Autowired
    private WaiterMapper             waiterMapper;
    @Autowired
    private WorkerMapper             workerMapper;
    @Autowired
    private DevSensetimeUploadMapper devSensetimeUploadMapper;

    @Autowired
    private RentMapper          rentMapper;
    @Autowired
    private TenantInHouseMapper tenantInHouseMapper;
    @Autowired
    private HousesMapper        housesMapper;

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private DevLockCardMapper devLockCardMapper;

    @Autowired
    private DevLockFingerprintMapper devLockFingerprintMapper;

    @Autowired
    private DevLockPasswordMapper devLockPasswordMapper;

    @Autowired
    private SmsService smsService;
    /**
     * 重写登录
     * @param user
     * @return
     * @throws Exception
     */
    public AppUser login(User user) throws Exception {
        if (user.getWxopenId() == null || Strings.isNullOrEmpty(user.getWxopenId())) {
            throw new Exception("请在微信小程序端登录");
        }
        String phone = user.getPhone();
        String pwd = user.getPwd();
        //判断手机号/身份证号/密码是否正确
        if (user.getPhone() != null && user.getPhone().length() != 11) {
            throw new Exception("手机号错误");
        }
        if (AppUserType.TENANT == user.getType() || AppUserType.FRIEND == user.getType()) {
            return checkTenant(phone,pwd,user.getWxopenId());
        } else if (AppUserType.LANDLORD == user.getType()) {
            //房東
            throw new Exception("暂不支持房东登陆");
        } else if (AppUserType.WORKER == user.getType()) {
            //获取对应的工人信息
            return checkWorker(phone,pwd);
        } else if (AppUserType.WAITER == user.getType()) {
            //获取对应的服务人员信息
            return checkWaiter(phone,pwd);
        } else if (AppUserType.COOPERATE == user.getType()) {
            //合作企業
            return checkEmployee(phone,pwd);
        } else {
            throw new Exception("错误的用户类型！");
        }
    }


    /**
     * 验证租客
     * @param phone
     * @param pwd
     * @return
     * @throws Exception
     */
    private AppUser checkTenant(String phone,String pwd,String openID)throws Exception{
        //获取租客信息
        Tenant query = new Tenant();
        query.setPhone(phone);
        query.setState(1);//有效
        List<Tenant> tenants = tenantMapper.select(query);
        if(tenants.isEmpty()||tenants.size()==0){
            throw new Exception("没有对应的租客信息");
        }
        if(tenants.size()> 1){//有多个记录
            throw new Exception("登录信息异常，请联系后台人员");
        }
        Tenant tenantOne = tenants.get(0);
        if (!tenantOne.getPwd().equals(pwd)) {
            throw new Exception("密码错误");
        }
        //验证是否有状态是3的用户
        query = new Tenant();
        query.setPhone(phone);
        query.setState(3);//临时
        int num = tenantMapper.selectCount(query);
        if(num>0){
            throw new Exception("用户尚未审核");
        }
        //登录成功则更新openid=====================
        Tenant tt = new Tenant();
        tt.setId(tenantOne.getId());
        tt.setWxopenId(openID);
        tenantMapper.updateByPrimaryKeySelective(tt);
        //登录成功则更新openid=====================
        return new AppUser(AppUserType.TENANT, tenantOne);
    }
    /**
     * 验证工人信息
     * @param phone
     * @param pwd
     * @return
     * @throws Exception
     */
    private AppUser checkWorker(String phone,String pwd)throws Exception{
        //获取对应的工人信息
        Worker query = new Worker();
        query.setPhone(phone);
        Worker worker = workerMapper.getWorkerInfoForLogin(query);
        if (worker == null) {
            throw new Exception("手机号码未注册！");
        }
        if (!worker.getPwd().equals(pwd)) {
            throw new Exception("密码错误");
        }
        return new AppUser(AppUserType.WORKER, worker);
    }

    /**
     * 验证服务人员信息
     * @param phone
     * @param pwd
     * @return
     * @throws Exception
     */
    private AppUser checkWaiter(String phone,String pwd)throws Exception{
        //获取对应的工人信息
        Waiter query = new Waiter();
        query.setPhone(phone);
        Waiter waiter = waiterMapper.getWaiterInfoForLogin(query);
        if (waiter == null) {
            throw new Exception("手机号码未注册！");
        }
        if (!waiter.getPwd().equals(pwd)) {
            throw new Exception("密码错误");
        }
        return new AppUser(AppUserType.WAITER, waiter);
    }

    /**
     * 验证企业合作人员
     * @param phone
     * @param pwd
     * @return
     * @throws Exception
     */
    private AppUser checkEmployee(String phone,String pwd)throws Exception{
        //获取对应的用户信息
        Employee query = new Employee();
        query.setPhone(phone);
        Employee employee = employeeMapper.getEmployeeInfoForLogin(query);
        if (employee == null) {
            throw new Exception("手机号码未注册！");
        }
        if (!employee.getPwd().equals(pwd)) {
            throw new Exception("密码错误");
        }
        return new AppUser(AppUserType.COOPERATE, employee);
    }


    @Override
    public String modify(User user) throws Exception {
        String cardId = null;
        int    i      = 0;
        //租客
        if (AppUserType.TENANT == user.getType() || AppUserType.FRIEND == user.getType()) {
            //判断手机号/身份证号/密码是否正确
            if (user.getPhone().length() < 11) {
                throw new Exception("手机号或身份证号错误");
            }
            //15位以上为身份证号
            if (user.getPwd().length() > 14) {
                cardId = user.getPhone();
            }
            //获取租客信息
            Tenant tenant = new Tenant();
            if (user.getPhone() != null && user.getPhone().length() < 15) {
                tenant.setPhone(user.getPhone());
            }
            if (cardId != null) {
                tenant.setCardId(cardId);
            }
            if (user.getWxopenId() == null || Strings.isNullOrEmpty(user.getWxopenId())) {
                throw new Exception("请在微信小程序端修改密码");
            } else {
                tenant.setWxopenId(user.getWxopenId());
            }
            tenant = tenantMapper.getTenantInfoForLogin(tenant);
            if (tenant == null) {
                throw new Exception("没有对应的租客信息");
            }
            if (!tenant.getPwd().equals(user.getPwd())) {
                throw new Exception("密码错误");
            }
            Tenant tenantNew = tenant;
            tenantNew.setPwd(user.getNewPwd());
            i = tenantMapper.updateByPrimaryKeySelective(tenantNew);
            //房東
        } else if (AppUserType.LANDLORD == user.getType()) {
            //判断手机号/身份证号/密码是否正确
                /*if(user.getPhone().length() < 11){
                    throw new Exception("手机号或身份证号错误");
                }*/
            //获取对应的用户信息

            throw new Exception("暂不支持房东登陆");
            //工人
        } else if (AppUserType.WORKER == user.getType()) {
            //判断手机号/身份证号/密码是否正确
            if (user.getPhone().length() < 11) {
                throw new Exception("手机号或身份证号错误");
            }
            //15位以上为身份证号
            if (user.getPwd().length() > 14) {
                cardId = user.getPhone();
            }
            //获取对应的工人信息
            Worker worker = new Worker();
            if (user.getPhone() != null && user.getPhone().length() < 15) {
                worker.setPhone(user.getPhone());
            }
            if (cardId != null) {
                worker.setCardId(cardId);
            }
            worker = workerMapper.getWorkerInfoForLogin(worker);
            if (worker == null) {
                throw new Exception("手机号码未注册！");
            }
            if (!worker.getPwd().equals(user.getPwd())) {
                throw new Exception("密码错误");
            }
            //修改密码
            if (worker != null && worker.getId() > 0) {
                Worker worker1 = worker;
                worker1.setPwd(user.getNewPwd());
                i = workerMapper.updateByPrimaryKeySelective(worker1);
            }


            //服务人员
        } else if (AppUserType.WAITER == user.getType()) {
            //判断手机号/身份证号/密码是否正确
            if (user.getPhone().length() < 11) {
                throw new Exception("手机号或身份证号错误");
            }
            //15位以上为身份证号
            if (user.getPwd().length() > 14) {
                cardId = user.getPhone();
            }
            //获取对应的用户信息
            Waiter waiter = new Waiter();
            if (user.getPhone() != null && user.getPhone().length() < 15) {
                waiter.setPhone(user.getPhone());
            }
            if (cardId != null) {
                waiter.setCardId(cardId);
            }
            waiter = waiterMapper.getWaiterInfoForLogin(waiter);
            if (waiter == null) {
                throw new Exception("手机号码未注册！");
            }
            if (!waiter.getPwd().equals(user.getPwd())) {
                throw new Exception("密码错误");
            }
            //修改密码
            if (waiter != null && waiter.getId() > 0) {
                Waiter waiter1 = waiter;
                waiter1.setPwd(user.getNewPwd());
                i = waiterMapper.updateByPrimaryKeySelective(waiter1);
            }

            //合作企業
        } else if (AppUserType.COOPERATE == user.getType()) {
            //判断手机号/身份证号/密码是否正确
            if (user.getPhone().length() < 11) {
                throw new Exception("手机号或身份证号错误");
            }
            //15位以上为身份证号
            if (user.getPwd().length() > 14) {
                cardId = user.getPhone();
            }
            //获取对应的用户信息
            Employee employee = new Employee();
            if (user.getPhone() != null && user.getPhone().length() < 15) {
                employee.setPhone(user.getPhone());
            }
            if (cardId != null) {
                employee.setCardId(cardId);
            }
            employee = employeeMapper.getEmployeeInfoForLogin(employee);
            if (employee == null) {
                throw new Exception("手机号码未注册！");
            }
            if (!employee.getPwd().equals(user.getPwd())) {
                throw new Exception("密码错误");
            }
            //修改密码
            if (employee != null && employee.getId() > 0) {
                Employee employee1 = employee;
                employee1.setPwd(user.getNewPwd());
                i = employeeMapper.updateByPrimaryKeySelective(employee1);
            }
        } else {
            throw new Exception("错误的用户类型！");
        }

        return i > 0 ? "ok" : "err";
    }

    @Override
    public String logon(User user) throws Exception {
        String result = "err";
        if (user.getWxopenId() == null || Strings.isNullOrEmpty(user.getWxopenId())) {
            throw new Exception("请在微信小程序端登陆！");
        }

        /* 默认身份证号码为唯一条件 20181023 王斌确认身份证唯一*/
        Example example = new Example(Tenant.class);
        example.createCriteria().
                andEqualTo("cardId", user.getCardId()).
                //andEqualTo("phone",user.getPhone()).
                        andNotEqualTo("state", 2);
        List<Tenant> tenants = tenantMapper.selectByExample(example);
        if (tenants == null || tenants.isEmpty()) {
            result = saveLogonInfo(user);
        } else {

            if (tenants.size() > 1) {
                throw new Exception("此身份证号码已经被注册多次，请联系管理员，核对证件号码！");
            } else {
                throw new Exception("你已经注册在使用，不能再次注册，如有需要信息更改，请联系管理员");
//                // 重置
//                reset(user, tenants.get(0));
//                //注册
//                result = saveLogonInfo(user);
            }
        }

//
//        ArrayList<Integer> arr = new ArrayList<>();
//        arr.add(1);
//        arr.add(3);
//        Example exampleCardId = new Example(Tenant.class);
//        exampleCardId.createCriteria().andIn("state",arr).andEqualTo("cardId",user.getCardId());
//        List<Tenant> tenantCardIdList = tenantMapper.selectByExample(exampleCardId);
//        Example  examplePhone = new Example(Tenant.class);
//        examplePhone.createCriteria().andIn("state",arr).andEqualTo("phone",user.getPhone());
//        List<Tenant> tenantPhoneList = tenantMapper.selectByExample(examplePhone);
//        Example exampleWxopenId = new Example(Tenant.class);
//        exampleWxopenId.createCriteria().andIn("state",arr).andEqualTo("wxopenId",user.getWxopenId());
//        List<Tenant> tenantWxopenIdList = tenantMapper.selectByExample(exampleWxopenId);
//
//        if(tenantCardIdList == null && tenantPhoneList == null && tenantWxopenIdList == null || (tenantPhoneList.isEmpty() && tenantCardIdList.isEmpty() && tenantWxopenIdList.isEmpty())){
//            result = saveLogonInfo(user);
//        }else if(tenantCardIdList != null && !tenantCardIdList.isEmpty()){
//            boolean flag = getRentInfo(tenantCardIdList.get(0).getId());
//            if(flag){
//                //重置
//                reset(user,tenantCardIdList.get(0));
//                //注册
//                result = saveLogonInfo(user);
//            }else{
//                throw new Exception("身份证号已注册，请联系管理员!");
//            }
//
//        }else if(tenantPhoneList != null && !tenantPhoneList.isEmpty()){
//            boolean flag = getRentInfo(tenantPhoneList.get(0).getId());
//            if(flag){
//                //重置
//                reset(user,tenantPhoneList.get(0));
//                //注册
//                result = saveLogonInfo(user);
//            }else{
//                throw new Exception("手机号重复，请联系管理员!");
//            }
//        } else if (tenantWxopenIdList != null && !tenantWxopenIdList.isEmpty() ) {
//           /* boolean flag = getRentInfo(tenantWxopenIdList.get(0).getId());
//            if(flag){
//                //重置
//                reset(user,tenantWxopenIdList.get(0));
//                //注册
//                result = saveLogonInfo(user);
//            }else{
//                throw new Exception("当前微信账号已经注册，请联系管理员!");
//            }*/
//            result = saveLogonInfo(user);
//        }
//

        if ("ok".equals(result) && user.getHouseId() != null) {
            Houses h = housesMapper.selectByPrimaryKey(user.getHouseId());
            if (h.getMaxCnt() == h.getInSumCnt()) {
                return "err";
            }
            TenantInHouse tenantInHouse = new TenantInHouse();
            tenantInHouse.setCardId(user.getCardId());
            tenantInHouse.setTenantName(user.getName());
            tenantInHouse.setHousesId(user.getHouseId());
            tenantInHouse.setPhone(user.getPhone());
            tenantInHouse.setEventTime(new Date());
            tenantInHouse.setState(1);
            tenantInHouse.setInfo1("小程序端注册预定");

            // 如果存在，更新，如果不存在新增

            Example tihExample = new Example(TenantInHouse.class);
            tihExample.createCriteria().
                    andEqualTo("cardId", user.getCardId()).
                    andEqualTo("state", 1);

            List<TenantInHouse> tihList = tenantInHouseMapper.selectByExample(tihExample);
            if (tihList == null || tihList.isEmpty()) {
                tenantInHouseMapper.insertSelective(tenantInHouse);
            } else {
                TenantInHouse temp = tihList.get(0);
                String info = temp.getHousesId() + "|"
                        + temp.getTenantName() + "|"
                        + temp.getEventTime() + "|"
                        + temp.getInfo1();
                tenantInHouse.setId(tihList.get(0).getId());
                tenantInHouse.setInfo1(info);
                tenantInHouseMapper.updateByPrimaryKeySelective(tenantInHouse);
            }


            //獲取房源所屬企業
            Long           l    = user.getHouseId();
            List<Employee> list = employeeMapper.getUsersByHouseId(l);
            //生成短信
            for (Employee e : list) {
                if (e.getPhone() != null) {
                    TenantInHouse t = new TenantInHouse();
                    t.setTenantName(user.getName());
                    t.setPhone(e.getPhone());
                    smsService.tenantSms(t);
                }
            }
        }
        return result;
    }

    //注册租客信息
    private String saveLogonInfo(User user) {
        Tenant tenant = new Tenant();
        tenant.setPhone(user.getPhone());
        tenant.setPwd(user.getPwd());
        tenant.setName(user.getName());
        if (user.getSex() != null) {
            tenant.setSex(user.getSex());
        }
        if (user.getEnterpriseName() != null) {
            tenant.setFormCompy(user.getEnterpriseName());
        }
        if (user.getNation() != null) {
            tenant.setNation(user.getNation());
        }
        tenant.setState(3);
        tenant.setType(1);
        if (user.getCardId() != null) {
            tenant.setCardId(user.getCardId());
        }
        tenant.setWxopenId(user.getWxopenId());
        tenant.setRemark("自助注册");
        return tenantMapper.insertSelective(tenant) > 0 ? "ok" : "fail";
    }

    //获取租房信息
    private boolean getRentInfo(Long id) {
        Example rentE = new Example(Rent.class);
        rentE.createCriteria().andEqualTo("tenantId", id).andEqualTo("state", 1);
        List<Rent> rentList = rentMapper.selectByExample(rentE);
        if (rentList == null || rentList.isEmpty()) {
            return true;
        } else {
            return false;
        }

    }

    //重置租客信息，一体机信息，指纹信息，卡信息，密码信息，
    private boolean reset(User user, Tenant tenantInfo) {
        //租客信息
        Tenant tenant = new Tenant();
        tenant.setId(tenantInfo.getId());
        tenant.setState(2);
        tenantMapper.updateByPrimaryKeySelective(tenant);
        //一体机
        Example uploadE = new Example(DevSensetimeUpload.class);
        uploadE.createCriteria().andEqualTo("id_number", tenantInfo.getCardId());
        DevSensetimeUpload devSensetimeUpload = new DevSensetimeUpload();
        devSensetimeUpload.setState(0);
        devSensetimeUploadMapper.updateByExampleSelective(devSensetimeUpload, uploadE);
        //指纹信息
        Example fingerE = new Example(DevLockFingerPrint.class);
        fingerE.createCriteria().andEqualTo("tenantId", tenantInfo.getId());
        DevLockFingerPrint devLockFingerPrint = new DevLockFingerPrint();
        devLockFingerPrint.setState(0);
        devLockFingerprintMapper.updateByExampleSelective(devLockFingerPrint, fingerE);
        //卡信息
        Example cardE = new Example(DevLockCard.class);
        cardE.createCriteria().andEqualTo("tenantId", tenantInfo.getId());
        DevLockCard devLockCard = new DevLockCard();
        devLockCard.setState(0);
        devLockCardMapper.updateByExampleSelective(devLockCard, cardE);
        //密码信息
        Example passwordE = new Example(DevLockPassword.class);
        passwordE.createCriteria().andEqualTo("tenantId", tenantInfo.getId());
        DevLockPassword devLockPassword = new DevLockPassword();
        devLockPassword.setState(0);
        devLockPasswordMapper.updateByExampleSelective(devLockPassword, passwordE);
        return true;
    }

    @Override
    public String randomNum(User user) throws Exception {
        //生成6位验证码
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        user.setRandomNum(verifyCode);
        smsService.randomSms(user);
        return verifyCode;
    }

    @Override
    public String checkPhone(User user) throws Exception {
        if (user.getPhone() != null) {
            Example      tenantE = new Example(Tenant.class);
            List<String> list    = new ArrayList<>();
            list.add("1");
            list.add("3");
            tenantE.createCriteria().andEqualTo("phone", user.getPhone()).andIn("state", list);
            List<Tenant> tenantList = tenantMapper.selectByExample(tenantE);
            if (tenantList != null && !tenantList.isEmpty()) {
                return "ok";
            }
        }
        return "err";
    }
}
